package system.data;

import java.util.Date;
import java.sql.Timestamp;

public class Convert {
	public static String toString(Object o) {
		return toString(o, "");
	}

	public static String toString(Object o, String defValue) {
		if (o == null)
			return defValue;
		return o.toString();
	}

	public static int toInt(Object o) {
		return toInt(o, 0);
	}

	public static int toInt(Object o, int defValue) {
		if (o == null)
			return defValue;
		if (o instanceof Integer)
			return ((Integer) o).intValue();

		try {
			return (int) Float.parseFloat(o.toString());
		} catch (Exception e) {
			return defValue;
		}
	}

	public static long toLong(Object o) {
		if (o == null)
			return 0L;
		if (o instanceof Long)
			return ((Long) o).longValue();

		try {
			return Long.parseLong(o.toString());
		} catch (Exception e) {
			return 0L;
		}
	}

	public static float toFloat(Object o) {
		if (o == null)
			return 0F;
		if (o instanceof Float)
			return ((Float) o).floatValue();

		try {
			return Float.parseFloat(o.toString());
		} catch (Exception e) {
			return 0F;
		}
	}

	public static boolean toBool(Object o) {
		if (o == null)
			return false;
		if (o instanceof Boolean)
			return ((Boolean) o).booleanValue();

		try {
			return Boolean.parseBoolean(o.toString());
		} catch (Exception e) {
			return false;
		}
	}

	public static Date toDate(Object o) {
		return toDate(o, new Date(System.currentTimeMillis()));
	}

	public static Date toDate(Object o, Date defValue) {
		if (o == null)
			return defValue;

		if (o instanceof java.util.Date)
			return (Date) o;

		try {
			return Timestamp.valueOf(o.toString());
		} catch (Exception e) {
			return defValue;
		}
	}
}